<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon online">
            <el-icon><VideoCamera></VideoCamera></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.onlineDevices }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </div>
        <div class="stat-trend">
          <el-icon class="trend-icon up"><ArrowUp></ArrowUp></el-icon>
          <span class="trend-text">+{{ statistics.deviceTrend }}%</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Monitor></Monitor></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalDevices }}</div>
            <div class="stat-label">总设备数</div>
          </div>
        </div>
        <div class="stat-trend">
          <el-icon class="trend-icon up"><ArrowUp></ArrowUp></el-icon>
          <span class="trend-text">+{{ statistics.totalTrend }}%</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon active">
            <el-icon><Connection></Connection></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.activeChannels }}</div>
            <div class="stat-label">活跃通道</div>
          </div>
        </div>
        <div class="stat-trend">
          <el-icon class="trend-icon up"><ArrowUp></ArrowUp></el-icon>
          <span class="trend-text">+{{ statistics.channelTrend }}%</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon streaming">
            <el-icon><VideoPlay></VideoPlay></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.streamingSessions }}</div>
            <div class="stat-label">流媒体会话</div>
          </div>
        </div>
        <div class="stat-trend">
          <el-icon class="trend-icon down"><ArrowDown></ArrowDown></el-icon>
          <span class="trend-text">-{{ statistics.streamingTrend }}%</span>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 设备状态分布 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>设备状态分布</span>
            <el-button-group size="small">
              <el-button
                :type="deviceChartType === 'pie' ? 'primary' : ''"
                @click="deviceChartType = 'pie'"
                >饼图</el-button
              >
              <el-button
                :type="deviceChartType === 'bar' ? 'primary' : ''"
                @click="deviceChartType = 'bar'"
                >柱图</el-button
              >
            </el-button-group>
          </div>
        </template>
        <div ref="deviceStatusChart" class="chart-container"></div>
      </el-card>

      <!-- 流量统计 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>流量统计</span>
            <el-select v-model="trafficPeriod" size="small" style="width: 100px">
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
            </el-select>
          </div>
        </template>
        <div ref="trafficChart" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 详细信息区域 -->
    <div class="details-grid">
      <!-- 最近事件 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>最近事件</span>
            <el-button text @click="viewAllEvents">查看全部</el-button>
          </div>
        </template>
        <div class="events-list">
          <div
            v-for="event in recentEvents"
            :key="event.id"
            class="event-item"
            :class="event.level"
          >
            <div class="event-icon">
              <el-icon><component :is="getEventIcon(event.type)"></component></el-icon>
            </div>
            <div class="event-content">
              <div class="event-title">{{ event.title }}</div>
              <div class="event-description">{{ event.description }}</div>
              <div class="event-time">{{ formatRelativeTime(event.createdAt) }}</div>
            </div>
            <div class="event-level">
              <el-tag :type="getEventLevelType(event.level)" size="small">
                {{ getEventLevelLabel(event.level) }}
              </el-tag>
            </div>
          </div>
          <div v-if="recentEvents.length === 0" class="no-events">
            <el-empty description="暂无事件" :image-size="80" />
          </div>
        </div>
      </el-card>

      <!-- 设备列表 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>设备状态</span>
            <el-button text @click="viewAllDevices">查看全部</el-button>
          </div>
        </template>
        <div class="devices-list">
          <div
            v-for="device in recentDevices"
            :key="device.id"
            class="device-item"
            @click="viewDevice(device)"
          >
            <div class="device-avatar">
              <el-avatar :size="40">
                <el-icon><VideoCamera></VideoCamera></el-icon>
              </el-avatar>
              <div class="device-status" :class="device.status"></div>
            </div>
            <div class="device-info">
              <div class="device-name">{{ device.name }}</div>
              <div class="device-details">
                <span class="device-ip">{{ device.ipAddress }}</span>
                <span class="device-manufacturer">{{ device.manufacturer }}</span>
              </div>
            </div>
            <div class="device-actions">
              <el-tag :type="getDeviceStatusType(device.status)" size="small">
                {{ getDeviceStatusLabel(device.status) }}
              </el-tag>
            </div>
          </div>
          <div v-if="recentDevices.length === 0" class="no-devices">
            <el-empty description="暂无设备" :image-size="80" />
          </div>
        </div>
      </el-card>

      <!-- 系统信息 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>系统信息</span>
            <el-button text @click="refreshSystemInfo">刷新</el-button>
          </div>
        </template>
        <div class="system-info">
          <div class="info-group">
            <div class="info-title">CPU使用率</div>
            <el-progress
              :percentage="systemInfo.cpuUsage"
              :color="getProgressColor(systemInfo.cpuUsage)"
              :show-text="true"
            />
          </div>
          <div class="info-group">
            <div class="info-title">内存使用率</div>
            <el-progress
              :percentage="systemInfo.memoryUsage"
              :color="getProgressColor(systemInfo.memoryUsage)"
              :show-text="true"
            />
          </div>
          <div class="info-group">
            <div class="info-title">磁盘使用率</div>
            <el-progress
              :percentage="systemInfo.diskUsage"
              :color="getProgressColor(systemInfo.diskUsage)"
              :show-text="true"
            />
          </div>
          <div class="info-group">
            <div class="info-title">网络带宽</div>
            <div class="bandwidth-info">
              <div class="bandwidth-item">
                <span class="label">上行:</span>
                <span class="value">{{ formatBitrate(systemInfo.networkUpload) }}</span>
              </div>
              <div class="bandwidth-item">
                <span class="label">下行:</span>
                <span class="value">{{ formatBitrate(systemInfo.networkDownload) }}</span>
              </div>
            </div>
          </div>
          <div class="info-group">
            <div class="info-title">运行时间</div>
            <div class="uptime">{{ formatDuration(systemInfo.uptime) }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <el-card shadow="hover">
        <template #header>
          <span>快速操作</span>
        </template>
        <div class="actions-grid">
          <el-button type="primary" :icon="Plus" @click="addDevice"> 添加设备 </el-button>
          <el-button type="success" :icon="Search" @click="discoverDevices"> 发现设备 </el-button>
          <el-button type="info" :icon="Refresh" @click="refreshAll"> 刷新状态 </el-button>
          <el-button type="warning" :icon="Setting" @click="openSettings"> 系统设置 </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useDeviceStore } from '@/stores/device'
import { formatRelativeTime, formatBitrate, formatDuration } from '@/utils/common'
import { DEVICE_STATUS_LABELS, DEVICE_STATUS_COLORS, EVENT_LEVEL_LABELS } from '@/utils/constants'
import {
  VideoCamera,
  Monitor,
  Connection,
  VideoPlay,
  ArrowUp,
  ArrowDown,
  Plus,
  Search,
  Refresh,
  Setting,
  Warning,
  InfoFilled,
  CircleClose
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const router = useRouter()
const deviceStore = useDeviceStore()

// 响应式数据
const deviceChartType = ref('pie')
const trafficPeriod = ref('today')
const deviceStatusChart = ref(null)
const trafficChart = ref(null)
const refreshTimer = ref(null)

// 统计数据
const statistics = reactive({
  onlineDevices: 0,
  totalDevices: 0,
  activeChannels: 0,
  streamingSessions: 0,
  deviceTrend: 0,
  totalTrend: 0,
  channelTrend: 0,
  streamingTrend: 0
})

// 最近事件
const recentEvents = ref([])

// 最近设备
const recentDevices = ref([])

// 系统信息
const systemInfo = reactive({
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0,
  networkUpload: 0,
  networkDownload: 0,
  uptime: 0
})

// 图表实例
let deviceChart = null
let trafficChartInstance = null

// 计算属性

// 方法
const getEventIcon = type => {
  const iconMap = {
    device_offline: CircleClose,
    stream_error: Warning,
    motion_detection: VideoCamera,
    system_error: InfoFilled,
    default: InfoFilled
  }
  return iconMap[type] || iconMap.default
}

const getEventLevelType = level => {
  const typeMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    critical: 'danger'
  }
  return typeMap[level] || 'info'
}

const getEventLevelLabel = level => {
  return EVENT_LEVEL_LABELS[level] || level
}

const getDeviceStatusType = status => {
  return DEVICE_STATUS_COLORS[status] || 'info'
}

const getDeviceStatusLabel = status => {
  return DEVICE_STATUS_LABELS[status] || status
}

const getProgressColor = percentage => {
  if (percentage < 60) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 初始化设备状态图表
const initDeviceStatusChart = () => {
  if (!deviceStatusChart.value) return

  deviceChart = echarts.init(deviceStatusChart.value)
  updateDeviceStatusChart()
}

// 更新设备状态图表
const updateDeviceStatusChart = () => {
  if (!deviceChart) return

  const data = [
    { name: '在线', value: statistics.onlineDevices, itemStyle: { color: '#67c23a' } },
    {
      name: '离线',
      value: statistics.totalDevices - statistics.onlineDevices,
      itemStyle: { color: '#f56c6c' }
    }
  ]

  const option =
    deviceChartType.value === 'pie'
      ? {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          series: [
            {
              name: '设备状态',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data
            }
          ]
        }
      : {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.name)
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '设备数量',
              type: 'bar',
              data: data.map(item => ({
                value: item.value,
                itemStyle: item.itemStyle
              }))
            }
          ]
        }

  deviceChart.setOption(option)
}

// 初始化流量图表
const initTrafficChart = () => {
  if (!trafficChart.value) return

  trafficChartInstance = echarts.init(trafficChart.value)
  updateTrafficChart()
}

// 更新流量图表
const updateTrafficChart = () => {
  if (!trafficChartInstance) return

  // 模拟数据
  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
  const uploadData = hours.map(() => Math.random() * 100)
  const downloadData = hours.map(() => Math.random() * 200)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['上行流量', '下行流量']
    },
    xAxis: {
      type: 'category',
      data: hours
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} MB/s'
      }
    },
    series: [
      {
        name: '上行流量',
        type: 'line',
        smooth: true,
        data: uploadData,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '下行流量',
        type: 'line',
        smooth: true,
        data: downloadData,
        itemStyle: { color: '#67c23a' }
      }
    ]
  }

  trafficChartInstance.setOption(option)
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const stats = await deviceStore.getStatistics()
    Object.assign(statistics, stats)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载最近事件
const loadRecentEvents = () => {
  // 模拟数据
  recentEvents.value = [
    {
      id: 1,
      type: 'device_offline',
      title: '设备离线',
      description: '摄像头001已离线',
      level: 'high',
      createdAt: new Date(Date.now() - 5 * 60 * 1000)
    },
    {
      id: 2,
      type: 'motion_detection',
      title: '移动检测',
      description: '通道002检测到移动',
      level: 'medium',
      createdAt: new Date(Date.now() - 15 * 60 * 1000)
    },
    {
      id: 3,
      type: 'stream_error',
      title: '流媒体错误',
      description: '通道003流媒体连接失败',
      level: 'high',
      createdAt: new Date(Date.now() - 30 * 60 * 1000)
    }
  ]
}

// 加载最近设备
const loadRecentDevices = () => {
  recentDevices.value = deviceStore.devices.slice(0, 5)
}

// 加载系统信息
const loadSystemInfo = () => {
  // 模拟数据
  systemInfo.cpuUsage = Math.floor(Math.random() * 100)
  systemInfo.memoryUsage = Math.floor(Math.random() * 100)
  systemInfo.diskUsage = Math.floor(Math.random() * 100)
  systemInfo.networkUpload = Math.random() * 1000000
  systemInfo.networkDownload = Math.random() * 10000000
  systemInfo.uptime = Math.floor(Math.random() * 86400 * 7)
}

// 刷新所有数据
const refreshAll = async () => {
  await Promise.all([loadStatistics(), loadRecentEvents(), loadRecentDevices(), loadSystemInfo()])

  updateDeviceStatusChart()
  updateTrafficChart()
}

// 刷新系统信息
const refreshSystemInfo = () => {
  loadSystemInfo()
}

// 查看所有事件
const viewAllEvents = () => {
  router.push('/events')
}

// 查看所有设备
const viewAllDevices = () => {
  router.push('/devices')
}

// 查看设备详情
const viewDevice = device => {
  router.push(`/devices/${device.id}`)
}

// 添加设备
const addDevice = () => {
  router.push('/devices/add')
}

// 发现设备
const discoverDevices = () => {
  router.push('/discovery')
}

// 打开设置
const openSettings = () => {
  router.push('/settings')
}

// 监听图表类型变化
watch(deviceChartType, () => {
  updateDeviceStatusChart()
})

// 监听流量周期变化
watch(trafficPeriod, () => {
  updateTrafficChart()
})

// 生命周期
onMounted(async () => {
  await refreshAll()

  nextTick(() => {
    initDeviceStatusChart()
    initTrafficChart()
  })

  // 设置定时刷新
  refreshTimer.value = setInterval(() => {
    loadSystemInfo()
    loadStatistics()
  }, 30000)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }

  if (deviceChart) {
    deviceChart.dispose()
  }

  if (trafficChartInstance) {
    trafficChartInstance.dispose()
  }

  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  if (deviceChart) {
    deviceChart.resize()
  }
  if (trafficChartInstance) {
    trafficChartInstance.resize()
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 0;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
    margin-bottom: 24px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 12px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: white;

          &.online {
            background: linear-gradient(135deg, #67c23a, #85ce61);
          }

          &.total {
            background: linear-gradient(135deg, #409eff, #66b1ff);
          }

          &.active {
            background: linear-gradient(135deg, #e6a23c, #ebb563);
          }

          &.streaming {
            background: linear-gradient(135deg, #f56c6c, #f78989);
          }
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-regular);
            margin-top: 4px;
          }
        }
      }

      .stat-trend {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;

        .trend-icon {
          font-size: 14px;

          &.up {
            color: var(--el-color-success);
          }

          &.down {
            color: var(--el-color-danger);
          }
        }

        .trend-text {
          color: var(--el-text-color-regular);
        }
      }
    }
  }

  .charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 24px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .details-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 16px;
    margin-bottom: 24px;

    .detail-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .events-list {
        max-height: 400px;
        overflow-y: auto;

        .event-item {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          padding: 12px 0;
          border-bottom: 1px solid var(--el-border-color-lighter);

          &:last-child {
            border-bottom: none;
          }

          .event-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: white;

            &.low {
              background: var(--el-color-info);
            }

            &.medium {
              background: var(--el-color-warning);
            }

            &.high,
            &.critical {
              background: var(--el-color-danger);
            }
          }

          .event-content {
            flex: 1;

            .event-title {
              font-weight: bold;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }

            .event-description {
              font-size: 14px;
              color: var(--el-text-color-regular);
              margin-bottom: 4px;
            }

            .event-time {
              font-size: 12px;
              color: var(--el-text-color-placeholder);
            }
          }

          .event-level {
            margin-top: 4px;
          }
        }

        .no-events {
          padding: 40px 0;
        }
      }

      .devices-list {
        max-height: 400px;
        overflow-y: auto;

        .device-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 12px 0;
          border-bottom: 1px solid var(--el-border-color-lighter);
          cursor: pointer;
          transition: background-color 0.2s;

          &:hover {
            background: var(--el-bg-color-page);
          }

          &:last-child {
            border-bottom: none;
          }

          .device-avatar {
            position: relative;

            .device-status {
              position: absolute;
              bottom: 0;
              right: 0;
              width: 12px;
              height: 12px;
              border-radius: 50%;
              border: 2px solid white;

              &.online {
                background: var(--el-color-success);
              }

              &.offline {
                background: var(--el-color-danger);
              }

              &.connecting {
                background: var(--el-color-warning);
              }
            }
          }

          .device-info {
            flex: 1;

            .device-name {
              font-weight: bold;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }

            .device-details {
              font-size: 12px;
              color: var(--el-text-color-regular);

              .device-ip {
                margin-right: 8px;
              }
            }
          }
        }

        .no-devices {
          padding: 40px 0;
        }
      }

      .system-info {
        .info-group {
          margin-bottom: 20px;

          &:last-child {
            margin-bottom: 0;
          }

          .info-title {
            font-size: 14px;
            color: var(--el-text-color-primary);
            margin-bottom: 8px;
          }

          .bandwidth-info {
            display: flex;
            justify-content: space-between;

            .bandwidth-item {
              .label {
                color: var(--el-text-color-regular);
                margin-right: 4px;
              }

              .value {
                color: var(--el-text-color-primary);
                font-weight: bold;
              }
            }
          }

          .uptime {
            font-size: 16px;
            color: var(--el-text-color-primary);
            font-weight: bold;
          }
        }
      }
    }
  }

  .quick-actions {
    .actions-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard {
    .stats-grid {
      grid-template-columns: 1fr;
    }

    .charts-grid {
      grid-template-columns: 1fr;
    }

    .details-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>
